/**
 * Created by Administrator on 2016/8/26.
 * 用于发布消息
 */
var express = require('express');
var router = express.Router();
var Article = require('../db/article');
var formidable = require('formidable');
var Photo=require('../db/photo');

var path=require('path');
var fs=require('fs');
var qn=require('../utils/qn');

function upload(files,res,flag,fields) {
    // var date = new Date();
    // var ms = Date.parse(date);
    // fs.rename(files.path,"./public/temp/"+ms+files.name);
    // var photo = new Photo({
    //     name: fields.title,
    //     path:"/temp/"+ms+files.name
    // });
    // photo.save(function (err, doc) {
    //     if (err) {
    //         flag="上传失败";
    //         res.render('upload',{ flag: files.name+"后的图片"+flag });
    //     } else {
    //         flag="上传成功";
    //     }
    // });
    var date = new Date();
    var ms = Date.parse(date);
    var key = ms+files.name;

    var token=qn.uptoken(key);
    qn.uploadFile(token, key, files.path);
    var photo = new Photo({
        name: fields.title,
        path: 'http://olpzuz4p9.bkt.clouddn.com/'+ms+files.name
    });


    photo.save(function (err, doc) {
        if (err) {
            flag="上传失败";
            res.render('upload',{ flag: files.name+"后的图片"+flag });
        } else {
            flag="上传成功";
        }
    });
}
function photos(req, res,callback) {
    var page = req.query.page;
    if (!page) {
        page = 1;
    }
    var pageSize = 10;

    console.log("page:" + page + ",rows:" + pageSize);

    var query = Photo.find({});
    query.skip((page - 1) * pageSize);
    query.limit(pageSize);
    //计算分页数据
    query.exec(function (err, docs) {
        if (err) {
            res.send(err);
        } else {
            //计算数据总数
            var policy =qn.policy();
            for (var i=0;i<docs.length;i++){
                docs[i].path = policy.makeRequest(docs[i].path);
            }
            Photo.find().count(function (err, count) {
                if (err) return;
                var  totalPages =Math.ceil(count / pageSize);
                callback(docs, count,page,totalPages);
            });
        }
    });
}
router.get('/photoEdit', function(req, res, next) {
    if (req.session.userid) {
        return next();
    }
    res.redirect('/login');
});
router.get('/photoEdit', function (req, res) {
    photos(req, res,function(docs, count,page,totalPages){

        res.render('photos1', {
            photos: docs,
            total: count,
            page: page,
            totalPages: totalPages
        });
    });

});


function index(req, res) {
    var page = req.query.page;
    if (!page) {
        page = 1;
    }
    var pageSize = 10;
    console.log("page:" + page + ",rows:" + pageSize);
    var query = Article.find({});
    query.skip((page - 1) * pageSize);
    query.limit(pageSize);
    //计算分页数据
    var obj="";
    query.exec(function (err, docs) {
        if (err) {
            res.send(err);
        } else {
            //计算数据总数
            Article.find().count(function (err, count) {
                if (err) return;
                var  totalPages =Math.ceil(count / pageSize);
                res.render('operator', {
                    title:"照片",
                    articles: docs,
                    total: count,
                    page: page,
                    totalPages: totalPages
                });
            });
        }
    });
}
router.get('/', function(req, res, next) {
    if (req.session.userid) {
        return next();
    }
    res.redirect('/login');
});
router.get('/', function (req, res) {
    index(req,res);
});
router.get('/logout',function (req,res) {
    if(req.session.userid||req.session.username){
        delete req.session.userid;
        delete req.session.username;
    }
    res.redirect('/login');
});
router.get('/edit', function(req, res, next) {
    if (req.session.userid) {
        return next();
    }
    res.redirect('/login');
});
router.get('/edit', function (req, res) {
    if(req.session.path||req.session.articleid){
        delete req.session.path;
        delete req.session.articleid;
    }
    var id=req.query.id;
    if(id){
        Article.findOne({_id:id},function (err,doc) {
            req.session.path=doc.content;
            req.session.articleid=doc._id;
            doc.content="/"+doc.content.split('./')[1];
            res.render('articleEdit',{article:doc});
        });
    }else{
        var doc={
            _id:"",
            title:"",
            content: "",
            author:"",
            authorId:"",
            creatTime:"",
            updateTime:"",
            describe:""
        };
        res.render('articleEdit',{article:doc});
    }
});
/*上传照片*/
router.get('/upload', function(req, res, next) {
    if (req.session.userid) {
        return next();
    }
    res.redirect('/login');
});
router.get('/upload', function(req, res, next) {
    res.render('upload',{ flag: '' });
});

router.post('/upload',function (req, res, next) {
    var form = new formidable.IncomingForm({
        // encoding:"utf-8",
        // uploadDir:"./public/temp",  //文件上传地址
        // keepExtensions:true , //保留后缀
        // multiples: true
    });
    var flag=" ";
    form.parse(req, function (error, fields, files) {
        try {
            if(!files.upload[0]){
                //调用uploadFile上传
                upload(files.upload,res,flag,fields);
                res.render('upload', {flag: "上传成功"});
            }else {
                for (var k in files.upload) {

                    upload(files.upload[k], res, flag,fields)
                }
                res.render('upload', {flag: "上传成功"});
            }
        } catch (e) {
            console.log(e);
            var response = { url: "" };
            res.end(JSON.stringify(response));
        }
    });

});

router.post('/ar_upload',function (req, res, next) {
    var form = new formidable.IncomingForm({
        encoding:"utf-8",
        uploadDir:"./public/temp1",  //文件上传地址
        keepExtensions:true , //保留后缀
        multiples: true
    });
    form.parse(req, function (error, fields, files) {
        res.json({path: "./"+files.file.path});
    });
});
/*删除文章*/
router.post('/delete', function(req, res, next) {
    var id=req.body.id;
    if(id && '' != id) {
        Article.remove({_id:id},function (err,doc) {
            var path="./public/"+req.body.path.split('./')[1];
            console.log(path);
            fs.unlink(path, function(err) {
                if (err) {
                    res.json({data:"fail"});
                }else{
                    res.json({data:"yes"});

                }
            });
        });
    }
});

module.exports = router;
